<template>
    <div class='userInfo'>
        <van-nav-bar title="个人信息" left-arrow @click-left="backUrl" />
        <div class="userImg" @click="changImage">
            <div class="head-img">
                <img v-if="userInfo.image !== ''" :src="userInfo.image" alt="" />
                <img v-else src="@/assets/default-avatar.png" alt="" />
            </div>
            <div class="tit">点击修改头像</div>
        </div>

        <!-- 修改图片弹窗 -->
        <van-action-sheet v-model="visiableImg" title="自定义图片" cancel-text="取消" close-on-click-action
            @cancel="onCancel">
            <van-uploader :after-read="uploadFile">
                <van-button round color="#7232dd" style="width: 370px;margin-left: 2px;">上传文件</van-button>
            </van-uploader>
        </van-action-sheet>
        <van-cell-group inset>
            <van-cell title="昵称" :value="userInfo.name" is-link @click="changeForm(1)" />
            <van-cell title="性别" :value="userInfo.sex" is-link @click="changeSex" />
            <van-cell title="简介" :value="userInfo.description" is-link @click="changeForm(2)" />
        </van-cell-group>
        <!-- 修改昵称，简介弹窗 -->
        <van-action-sheet v-model="visiableForm" :title="'修改' + label.title">
            <div class="form">
                <van-field v-if="label.id === 1" v-model="userInfo.name" :label="label.title"
                    :placeholder="'请输入' + label.title" />
                <van-field v-if="label.id === 2" v-model="userInfo.description" :label="label.title"
                    :placeholder="'请输入' + label.title" />
                <van-button round color="#7232dd" style="width: 300px" @click="editUserInfo">保存</van-button>
            </div>
        </van-action-sheet>
        <!-- 修改性别弹窗 -->
        <van-action-sheet v-model="visiableSex" :actions="actions" cancel-text="取消" close-on-click-action
            @cancel="onCancel" @select="selectSex" />
    </div>
</template>

<script>
// 这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
// 例如：import 《组件名称》 from '《组件路径》';
import request from '@/utils/request'

export default {
  name: '',
  // import引入的组件需要注入到对象中才能使用
  components: {},
  data () {
  // 这里存放数据
    return {
      baseUserInfo: '/user-info',
      labelList: [{ id: 1, title: '昵称' }, { id: 2, title: '简介' }],
      actions: [{ name: '保密' }, { name: '男' }, { name: '女' }],
      label: {},
      visiableImg: false,
      visiableForm: false,
      visiableSex: false,
      userInfo: {
        id: 0,
        image: '',
        name: '',
        sex: '',
        description: ''
      }
    }
  },
  // 监听属性 类似于data概念
  computed: {},
  // 监控data中的数据变化
  watch: {},
  // 方法集合
  methods: {
    backUrl () {
      const url = this.$route.query.backUrl || '/'
      this.$router.replace(url)
    },
    // 切换头像
    changImage () {
      this.visiableImg = true
    },
    changeForm (id) {
      this.visiableForm = true
      this.labelList.forEach(item => {
        if (item.id === id) {
          this.label = item
        }
      })
    },
    changeSex () {
      this.visiableSex = true
    },
    // 提交修改过的个人信息
    editUserInfo () {
      this.editInfo()
    },
    selectSex (action, index) {
      this.actions.forEach(item => {
        if (item.name === action.name) {
          this.userInfo.sex = item.name
        }
      })
      this.editInfo()
    },
    onCancel () {
      this.visiableImg = false
      this.visiableSex = false
    },
    async uploadFile (file) {
      // 此时可以自行将文件上传至服务器
      const fileData = new FormData()
      fileData.append('file', file.file)
      const res = await request.post(
        '/file/upload-file',
        fileData,
        {
          'Content-Type': 'multipart/form-data;charset=utf-8'
        }
      )
      this.userInfo.image = res.data.data
      await this.editInfo()
    },
    // 编辑个人信息
    async editInfo () {
      await request({
        url: this.baseUserInfo + '/user-info',
        method: 'put',
        data: this.userInfo
      }).then(() => {
        this.visiableForm = false
        this.visiableImg = false
        this.visiableSex = false
      })
    },
    // 回显个人信息
    async getInfo () {
      await request({
        url: this.baseUserInfo + '/user-info',
        method: 'get'
      }).then(res => {
        this.userInfo = res.data.data
      })
    }
  },
  // 生命周期 - 创建完成（可以访问当前this实例）
  created () {
    this.getInfo()
  },
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted () {

  },
  beforeCreate () {}, // 生命周期 - 创建之前
  beforeMount () {}, // 生命周期 - 挂载之前
  beforeUpdate () {}, // 生命周期 - 更新之前
  updated () {}, // 生命周期 - 更新之后
  beforeDestroy () {}, // 生命周期 - 销毁之前
  destroyed () {}, // 生命周期 - 销毁完成
  activated () {} // 如果页面有keep-alive缓存功能，这个函数会触发
}
</script>
<style lang="less" scoped>
.userImg {
    .head-img {
        width: 80px;
        height: 80px;
        border-radius: 50%;
        overflow: hidden;
        margin: 10px auto;

        img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }
    }
    .tit {
        margin-top: 3px;
        font-size: 12px;
        text-align: center;
    }
}

.van-uploader {
    margin: 10px auto;
}
.userInfo {
  ::v-deep .van-icon-arrow-left {
    color: #333;
  }

  min-height: 100vh;
  background-color: #f7f7f7;

  .van-cell-group {
    margin-top: 10px;
  }

  .img {
    margin: 10px auto;
    width: 100px;
    height: 100px;
    background-color: #fff;
    padding: 5px;
  }
}

.form {
    margin: 10px;
    text-align: center;

    .van-button  {
        margin-top: 10px;
    }
}
</style>
